package com.kadron.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.KApplicationImage;
import com.kadron.entity.KImage;
import com.kadron.entity.KItemImage;

@AutoCreate
@BypassInterceptors
@Name("imageDAO")
@Scope(ScopeType.EVENT)
public class KImageDAO extends KDAO<KApplicationImage> {

	@SuppressWarnings("unchecked")
	public List<KImage> getApplicationImages(long applicationId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT i FROM KApplicationImage i WHERE i.applicationId = :application_id ORDER BY i.position")
			.setParameter("application_id", applicationId)
			.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<KItemImage> getItemImages(long itemId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT i FROM KItemImage i WHERE i.itemId = :item_id ORDER BY i.position")
		.setParameter("item_id", itemId)
		.getResultList();
	}
	
	public KApplicationImage getApplicationImage(long applciationId) {
		EntityManager em = getEntityManager();
		try {			
			return (KApplicationImage) em.createQuery("SELECT i FROM KApplicationImage i WHERE i.applicationId = :application_id AND i.main=TRUE")
			.setParameter("application_id", applciationId)
			.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public void updateItemImageNotMain(long itemId) {
		EntityManager em = getEntityManager();
		em.createQuery("UPDATE KItemImage i SET main=FALSE WHERE i.itemId = :item_id")
		.setParameter("item_id", itemId)
		.executeUpdate();
	}
	
	public void updateApplicationImageNotMain(long applciationId) {
		EntityManager em = getEntityManager();
		em.createQuery("UPDATE KApplicationImage i SET main=FALSE WHERE i.applicationId = :application_id")
		.setParameter("application_id", applciationId)
		.executeUpdate();
	}
	
	public KItemImage getMainItemImage(long itemId) {
		EntityManager em = getEntityManager();
		try {
			KItemImage img = (KItemImage) em.createQuery("SELECT i FROM KItemImage i WHERE i.itemId = :item_id AND i.main=TRUE")
			.setParameter("item_id", itemId)
			.setMaxResults(1)
			.getSingleResult();	
			return img;
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public KItemImage getItemImage(long itemId) {
		EntityManager em = getEntityManager();
		try {
			KItemImage img = (KItemImage) em.createQuery("SELECT i FROM KItemImage i WHERE i.itemId = :item_id")
			.setParameter("item_id", itemId)
			.setMaxResults(1)
			.getSingleResult();			
			return img;
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
